
//
// 121022 - (AH) - (Midtun) Created.
//

package org.soekrat.engine.socraton;

import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.util.List;


/**
 * <p>
 *   Object that defines the XML dialect of
 *   {@link Socratons}.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
public final class SocratonsXml 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public SocratonsXml(){}
 
  
  public String compile(Socratons socratons)
  {
    if (socratons==null)
    {
      throw new NullPointerException("socratons");
    }
    
    CharArrayWriter caw=new CharArrayWriter();
    PrintWriter pw=new PrintWriter(caw);
    
    compile(socratons, pw);
    
    return caw.toString();
  }
  
  public void compile(Socratons socratons, PrintWriter pw)
  {
    if (socratons==null)
    {
      throw new NullPointerException("socratons");
    }
    if (pw==null)
    {
      throw new NullPointerException("pw");
    }
    
    pw.println("<?xml version='1.0' encoding='UTF-8'?>");
    
    pw.println("<socratons>");
    
    StringBuilder sb=new StringBuilder();
    
    for (Socraton curr : socratons)
    {
      Object id=curr.getId();
      sb.append("  <socraton id='").append(id).append("'>");
      pw.println(sb.toString());
      sb.setLength(0);
      
      List<String> contexts=curr.getContexts();
      for (String ctx : contexts)
      {
        sb.append("    <context name='").append(ctx).append("'>");
        pw.println(sb.toString());
        sb.setLength(0);
        
        Bison[] bisons=curr.getBisons(ctx);
        for (Bison bison : bisons)
        {
          sb.append("      <bison data='").append(bison.getLocation())
            .append("' />");
          pw.println(sb.toString());
          sb.setLength(0);
        }
        
        pw.println("    </context>");
      }
      
      pw.println("  </socraton>");
    }
    
    pw.println("</socratons>");
    
    pw.flush();
  }
  
}
